<?php

namespace App\Admin\Controllers\Config;

use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use App\Models\Config\SystemDictDatum;
use Dcat\Admin\Http\Controllers\AdminController;

class DictDatumController extends AdminController
{
    public function __construct()
    {
        Admin::translator()->setPath("dict");
    }

    public function title()
    {
        return admin_trans_label("dict-datum");
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $dict_id = request("dict_id");

        $model = SystemDictDatum::when($dict_id,function ($query) use($dict_id){
            return $query->where("dict_id",$dict_id);
        });

        $grid =  Grid::make($model, function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('dict_label')->editable();
            $grid->column('dict_value')->editable();
            $grid->column('sort')->sortable()->orderable();
            $grid->column('state')->select(["0"=>"关闭","1"=>"开启"])->width(100);
            $grid->column('remark')->limit(20)->width(250);;
            $grid->column('created_at')->width(170);
            $grid->column('updated_at')->sortable()->width(170);

            #$grid->withBorder();
            $grid->enableDialogCreate();
            $grid->showQuickEditButton();
            $grid->disableBatchActions();
            $grid->disableRowSelector();
            $grid->disableEditButton();
            $grid->disableViewButton();
            $grid->disablePagination();
        });
        $grid->model()->setConstraints(["dict_id"=>$dict_id]);


        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $key = request()->get("dict_id");

        $form = Form::make(new SystemDictDatum(), function (Form $form) use($key){
            if ($key){
                $form->hidden("dict_id")->value($key);
            }
            $form->text('dict_label');
            $form->text('dict_value');
            $form->text('sort');
            $form->switch('state')->default(1);
            $form->textarea('remark');
        });

        $form->saving(function (Form $form) use($key){
            if ($form->isCreating() && !$key) {
                throw new \Exception("无法添加字典值！");
            }
        });
        return $form;
    }
}
